package com.haohan.cloud.scm.aftersales.core.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.haohan.cloud.scm.aftersales.core.ScmReturnOrderService;
import com.haohan.cloud.scm.aftersales.service.ReturnOrderDetailService;
import com.haohan.cloud.scm.aftersales.service.ReturnOrderService;
import com.haohan.cloud.scm.aftersales.utils.ScmAfterSalesUtils;
import com.haohan.cloud.scm.api.aftersales.entity.ReturnOrder;
import com.haohan.cloud.scm.api.aftersales.entity.ReturnOrderDetail;
import com.haohan.cloud.scm.api.aftersales.req.AddBuyReturnOrderReq;
import com.haohan.cloud.scm.api.aftersales.req.AddReturnOrderByOfferReq;
import com.haohan.cloud.scm.api.aftersales.req.AddReturnOrderReq;
import com.haohan.cloud.scm.api.aftersales.req.EditReturnOrderReq;
import com.haohan.cloud.scm.api.aftersales.resp.QueryReturnOrderDetailResp;
import com.haohan.cloud.scm.api.aftersales.resp.ReturnOrderResp;
import com.haohan.cloud.scm.api.aftersales.trans.AddReturnOrderTrans;
import com.haohan.cloud.scm.api.bill.entity.PayableBill;
import com.haohan.cloud.scm.api.bill.entity.ReceivableBill;
import com.haohan.cloud.scm.api.constant.NumberPrefixConstant;
import com.haohan.cloud.scm.api.constant.enums.aftersales.ReturnStatusEnum;
import com.haohan.cloud.scm.api.constant.enums.aftersales.ReturnTypeEnum;
import com.haohan.cloud.scm.api.constant.enums.manage.PhotoTypeEnum;
import com.haohan.cloud.scm.api.constant.enums.purchase.PurchaseStatusEnum;
import com.haohan.cloud.scm.api.constant.enums.supply.PdsOfferStatusEnum;
import com.haohan.cloud.scm.api.constant.enums.supply.ShipStatusEnum;
import com.haohan.cloud.scm.api.goods.dto.GoodsModelDTO;
import com.haohan.cloud.scm.api.goods.feign.GoodsModelFeignService;
import com.haohan.cloud.scm.api.manage.dto.PhotoGroupDTO;
import com.haohan.cloud.scm.api.opc.entity.BuyerPayment;
import com.haohan.cloud.scm.api.opc.entity.SupplierPayment;
import com.haohan.cloud.scm.api.opc.req.payment.BuyerPaymentReq;
import com.haohan.cloud.scm.api.opc.req.payment.SupplierPaymentReq;
import com.haohan.cloud.scm.api.product.entity.ProductInfo;
import com.haohan.cloud.scm.api.product.feign.ProductInfoFeignService;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseOrder;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseOrderDetail;
import com.haohan.cloud.scm.api.purchase.feign.PurchaseOrderDetailFeignService;
import com.haohan.cloud.scm.api.purchase.feign.PurchaseOrderFeignService;
import com.haohan.cloud.scm.api.purchase.req.PurchaseOrderDetailReq;
import com.haohan.cloud.scm.api.purchase.req.PurchaseOrderReq;
import com.haohan.cloud.scm.api.saleb.entity.BuyOrder;
import com.haohan.cloud.scm.api.saleb.entity.BuyOrderDetail;
import com.haohan.cloud.scm.api.saleb.entity.Buyer;
import com.haohan.cloud.scm.api.saleb.feign.BuyOrderDetailFeignService;
import com.haohan.cloud.scm.api.saleb.feign.BuyOrderFeignService;
import com.haohan.cloud.scm.api.saleb.feign.BuyerFeignService;
import com.haohan.cloud.scm.api.saleb.feign.BuyerPaymentFeignService;
import com.haohan.cloud.scm.api.saleb.req.BuyOrderDetailReq;
import com.haohan.cloud.scm.api.saleb.req.BuyOrderReq;
import com.haohan.cloud.scm.api.supply.feign.SupplierPaymentFeignService;
import com.haohan.cloud.scm.api.wms.entity.EnterWarehouse;
import com.haohan.cloud.scm.api.wms.entity.EnterWarehouseDetail;
import com.haohan.cloud.scm.api.wms.entity.WarehouseStock;
import com.haohan.cloud.scm.api.wms.feign.EnterWarehouseDetailFeignService;
import com.haohan.cloud.scm.api.wms.feign.EnterWarehouseFeignService;
import com.haohan.cloud.scm.common.tools.exception.EmptyDataException;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.common.tools.util.ScmIncrementUtil;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xwx
 * @date 2019/7/23
 */
@Service
@AllArgsConstructor
public class ScmReturnOrderServiceImpl implements ScmReturnOrderService {

    private final ScmIncrementUtil scmIncrementUtil;
    private final PurchaseOrderDetailFeignService purchaseOrderDetailFeignService;
    private final PurchaseOrderFeignService purchaseOrderFeignService;
    private final ReturnOrderDetailService returnOrderDetailService;
    private final ReturnOrderService returnOrderService;
    private final BuyOrderFeignService buyOrderFeignService;
    private final BuyOrderDetailFeignService buyOrderDetailFeignService;
    private final GoodsModelFeignService goodsModelFeignService;
    private final BuyerFeignService buyerFeignService;
    private final ProductInfoFeignService productInfoFeignService;
    private final EnterWarehouseFeignService enterWarehouseFeignService;
    private final EnterWarehouseDetailFeignService enterWarehouseDetailFeignService;
    private final ScmAfterSalesUtils scmAfterSalesUtils;

    /**
     * 查询退货单应退金额
     * @param list
     * @return
     */
    @Override
    public List<ReturnOrderResp> queryReturnOrderAmount(List list) {
        List<ReturnOrderResp> orders = new ArrayList<>();
        for(Object obj:list) {
            ReturnOrder order = BeanUtil.toBean(obj, ReturnOrder.class);
            ReturnOrderResp resp = new ReturnOrderResp();
            BeanUtil.copyProperties(order,resp);
            if(order.getReturnType() == ReturnTypeEnum.customer){
                //b客户
                PayableBill bill = scmAfterSalesUtils.fetchPayableBill(order.getPaymentSn());
                resp.setReturnAmount(bill.getBillAmount());
            }else{
                //采购
                ReceivableBill bill = scmAfterSalesUtils.fetchReceivableBill(order.getPaymentSn());
                resp.setReturnAmount(bill.getBillAmount());
            }
            orders.add(resp);
        }
        return orders;
    }

    /**
     * 保存 退货图片组
     * @param merchantId
     * @param photoList
     * @return
     */
    private String savePhotoGroup(String merchantId, String groupNum, List<String> photoList){
        PhotoGroupDTO photoGroupDTO = new PhotoGroupDTO();
        photoGroupDTO.setMerchantId(merchantId);
        photoGroupDTO.setGroupNum(groupNum);
        photoGroupDTO.setCategoryTag(PhotoTypeEnum.back.getDesc());
        photoGroupDTO.setGroupName("退货图片");
        photoGroupDTO.transPhotoList(photoList);
        return scmAfterSalesUtils.savePhotoGroup(photoGroupDTO);
    }

    /**
     * 新增退货单
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addReturnOrder(AddReturnOrderReq req) {
        PurchaseOrderReq query = new PurchaseOrderReq();
        query.setPmId(req.getPmId());
        query.setPurchaseSn(req.getPurchaseSn());
        R r = purchaseOrderFeignService.getOneByPurchaseOrderReq(query, SecurityConstants.FROM_IN);
        if(!RUtil.isSuccess(r) || ObjectUtil.isNull(r.getData())){
            throw new EmptyDataException();
        }
        PurchaseOrder o = BeanUtil.toBean(r.getData(), PurchaseOrder.class);
        Map<String,ReturnOrder> map = new LinkedHashMap<>();
        for(PurchaseOrderDetail detail : req.getDetailList()){
            PurchaseOrderDetailReq q = new PurchaseOrderDetailReq();
            q.setPmId(req.getPmId());
            q.setPurchaseSn(req.getPurchaseSn());
            q.setPurchaseDetailSn(detail.getPurchaseDetailSn());
            R dr = purchaseOrderDetailFeignService.getOneByPurchaseOrderDetailReq(q, SecurityConstants.FROM_IN);
            if(!RUtil.isSuccess(dr) || ObjectUtil.isNull(dr.getData())){
                throw new EmptyDataException();
            }
            PurchaseOrderDetail d = BeanUtil.toBean(dr.getData(), PurchaseOrderDetail.class);
            ReturnOrderDetail orderDetail = AddReturnOrderTrans.initReturnOrderDetailTrans(d);
            String dsn = scmIncrementUtil.inrcSnByClass(ReturnOrderDetail.class, NumberPrefixConstant.RETURN_DETAIL_SN_PRE);
            orderDetail.setReturnDetailSn(dsn);
            if(ObjectUtil.isNull(map.get(d.getSupplierId()))){
                String sn = scmIncrementUtil.inrcSnByClass(ReturnOrder.class, NumberPrefixConstant.RETURN_ORDER_SN_PRE);
                orderDetail.setReturnSn(sn);
                ReturnOrder order = new ReturnOrder();
                order.setGoodsNum(BigDecimal.ZERO);
                order.setPmId(o.getPmId());
                order.setReturnSn(sn);
                order.setOrderSn(o.getPurchaseSn());
                order.setGoodsNum(order.getGoodsNum().add(BigDecimal.ONE));
                order.setSumAmount(d.getRealBuyNum().multiply(d.getBuyPrice()));
                order.setReturnStatus(ReturnStatusEnum.wait);
                order.setReturnType(ReturnTypeEnum.getByType(req.getReturnType()));
                order.setReturnCustomerId(d.getSupplierId());
                order.setReturnCustomer(d.getSupplierName());
                order.setOtherAmount(req.getOtherAmount());
                map.put(d.getSupplierId(),order);
            }else{
                ReturnOrder order = map.get(d.getSupplierId());
                orderDetail.setReturnSn(order.getReturnSn());
                order.setSumAmount(order.getSumAmount().add(d.getRealBuyNum().multiply(d.getBuyPrice())));
                order.setGoodsNum(order.getGoodsNum().add(BigDecimal.ONE));
            }
            if(!returnOrderDetailService.save(orderDetail)){
                throw new ErrorDataException();
            }
            d.setPurchaseStatus(PurchaseStatusEnum.close);
            if(!RUtil.isSuccess(purchaseOrderDetailFeignService.updateById(d,SecurityConstants.FROM_IN))){
                throw new ErrorDataException();
            }
        }
        for(Object obj : map.keySet()){
            ReturnOrder order = map.get(obj);
            order.setTotalAmount(order.getSumAmount().add(order.getOtherAmount()));
            // 保存图片组
            order.setPhotoGroupNum(savePhotoGroup(order.getPmId(), "",req.getPhotoList()));
            if(!returnOrderService.save(order)){
                throw new ErrorDataException();
            }
        }
        return true;
    }

    /**
     * 订单退货
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean buyOrderReturn(AddBuyReturnOrderReq req) {
        BuyOrderReq q = new BuyOrderReq();
        q.setPmId(req.getPmId());
        q.setBuyId(req.getBuyId());
        R r = buyOrderFeignService.getOneByBuyOrderReq(q, SecurityConstants.FROM_IN);
        if(!RUtil.isSuccess(r) || r.getData() == null){
            throw new EmptyDataException();
        }
        BuyOrder o = BeanUtil.toBean(r.getData(), BuyOrder.class);
        Map<String,ReturnOrder> map = new LinkedHashMap<>();
        for(BuyOrderDetail detail : req.getDetailList()){
            BuyOrderDetailReq que = new BuyOrderDetailReq();
            que.setPmId(detail.getPmId());
            que.setBuyDetailSn(detail.getBuyDetailSn());
            que.setBuyId(detail.getBuyId());
            R res = buyOrderDetailFeignService.getOneByBuyOrderDetailReq(que, SecurityConstants.FROM_IN);
            if(!RUtil.isSuccess(res) || res.getData() == null){
                throw new EmptyDataException();
            }
            BuyOrderDetail de = BeanUtil.toBean(res.getData(), BuyOrderDetail.class);
            de.setGoodsNum(detail.getGoodsNum());
            R<GoodsModelDTO> bi = goodsModelFeignService.getInfoById(de.getGoodsModelId(), SecurityConstants.FROM_IN);
            if(!RUtil.isSuccess(bi) || bi.getData() == null){
                throw new EmptyDataException();
            }
            GoodsModelDTO dto = BeanUtil.toBean(bi.getData(), GoodsModelDTO.class);
            ReturnOrderDetail orderDetail = AddReturnOrderTrans.initBuyOrderDetailReturn(de, dto);
            if(ObjectUtil.isNull(map.get(de.getBuyerId()))){
                String sn = scmIncrementUtil.inrcSnByClass(ReturnOrder.class, NumberPrefixConstant.RETURN_ORDER_SN_PRE);
                orderDetail.setReturnSn(sn);
                ReturnOrder order = new ReturnOrder();
                order.setGoodsNum(BigDecimal.ZERO);
                order.setPmId(o.getPmId());
                order.setReturnSn(sn);
                order.setOrderSn(o.getBuyId());
                order.setGoodsNum(order.getGoodsNum().add(BigDecimal.ONE));
                order.setSumAmount(de.getGoodsNum().multiply(de.getBuyPrice()));
                order.setReturnStatus(ReturnStatusEnum.wait);
                order.setReturnType(ReturnTypeEnum.getByType(req.getReturnType()));
                order.setReturnCustomerId(de.getBuyerId());
                R byId = buyerFeignService.getById(de.getBuyerId(), SecurityConstants.FROM_IN);
                if(!RUtil.isSuccess(byId) || byId.getData() == null){
                    throw new EmptyDataException();
                }
                Buyer buyer = BeanUtil.toBean(byId.getData(), Buyer.class);
                order.setReturnCustomer(buyer.getBuyerName());
                order.setOtherAmount(req.getOtherAmount());
                map.put(de.getBuyerId(),order);
            }else{
                ReturnOrder order = map.get(de.getBuyerId());
                orderDetail.setReturnSn(order.getReturnSn());
                order.setSumAmount(order.getSumAmount().add(de.getGoodsNum().multiply(de.getBuyPrice())));
                order.setGoodsNum(order.getGoodsNum().add(BigDecimal.ONE));
            }
            if(!returnOrderDetailService.save(orderDetail)){
                throw new ErrorDataException();
            }
        }
        for(Object obj : map.keySet()){
            ReturnOrder order = map.get(obj);
            order.setReturnReason(req.getReturnReason());
            order.setTotalAmount(order.getSumAmount().add(req.getOtherAmount()));
            // 保存图片组
            order.setPhotoGroupNum(savePhotoGroup(order.getPmId(), "",req.getPhotoList()));
            if(!returnOrderService.save(order)){
                throw new ErrorDataException();
            }
        }
        return true;
    }

    /**
     * 查看退货单详情
     * @param order
     * @return
     */
    @Override
    public QueryReturnOrderDetailResp queryReturnOrderDetail(ReturnOrder order) {
        QueryReturnOrderDetailResp resp = new QueryReturnOrderDetailResp();
        ReturnOrder query = new ReturnOrder();
        query.setPmId(order.getPmId());
        query.setReturnSn(order.getReturnSn());
        ReturnOrder one = returnOrderService.getOne(Wrappers.query(query));
        if(ObjectUtil.isNull(one)){
            throw new EmptyDataException();
        }
        ReturnOrderDetail q = new ReturnOrderDetail();
        q.setPmId(order.getPmId());
        q.setReturnSn(order.getReturnSn());
        QueryWrapper<ReturnOrderDetail>  wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ReturnOrderDetail::getReturnSn,one.getReturnSn())
                .eq(ReturnOrderDetail::getPmId,one.getPmId());
        List<ReturnOrderDetail> list = returnOrderDetailService.list(wrapper);
        if(list.isEmpty()){
            throw new EmptyDataException();
        }
        BeanUtil.copyProperties(one,resp);
        resp.setDetailList(list);
        // 图片组
        resp.setPhotoList(scmAfterSalesUtils.fetchPhotoGroup(one.getPhotoGroupNum()));
        return resp;
    }

    /**
     * 编辑退货单
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean editReturnOrder(EditReturnOrderReq req) {
        ReturnOrder upd = new ReturnOrder();
        BeanUtil.copyProperties(req,upd);
        upd.setSumAmount(BigDecimal.ZERO);
        req.getEditDetails().forEach(detail -> {
            ReturnOrderDetail d = new ReturnOrderDetail();
            if(null != returnOrderDetailService.getById(detail.getId())){
                BeanUtil.copyProperties(detail,d);
                d.setGoodsAmount(d.getGoodsNum().multiply(d.getGoodsPrice()));
                upd.setSumAmount(upd.getSumAmount().add(d.getGoodsAmount()));
                if(!returnOrderDetailService.updateById(detail)){
                    throw new ErrorDataException();
                }
            }else{
                throw new EmptyDataException();
            }
        });
        upd.setTotalAmount(upd.getSumAmount().add(req.getOtherAmount()));
        // 保存图片组
        upd.setPhotoGroupNum(savePhotoGroup(req.getPmId(), req.getPhotoGroupNum(), req.getPhotoList()));
        if(!returnOrderService.updateById(upd)){
            throw new ErrorDataException();
        }
        if(!req.getDelDetails().isEmpty()){
            req.getDelDetails().forEach(details -> {
                if(!returnOrderDetailService.removeById(details.getId())){
                    throw new ErrorDataException();
                }
            });
        }
        if(!req.getAddDetails().isEmpty()){
            req.getAddDetails().forEach(details -> {
                ReturnOrderDetail save = new ReturnOrderDetail();
                if(req.getReturnType() == ReturnTypeEnum.customer){
                    R r = buyOrderDetailFeignService.getById(details.getId(), SecurityConstants.FROM_IN);
                    if(!RUtil.isSuccess(r) || r.getData() == null){
                        throw new EmptyDataException();
                    }
                    BuyOrderDetail detail = BeanUtil.toBean(r.getData(), BuyOrderDetail.class);
                    R byId = goodsModelFeignService.getById(detail.getGoodsModelId(), SecurityConstants.FROM_IN);
                    if(!RUtil.isSuccess(byId) || byId.getData() == null){
                        throw new EmptyDataException();
                    }
                    GoodsModelDTO dto = BeanUtil.toBean(byId, GoodsModelDTO.class);
                    save = AddReturnOrderTrans.initBuyOrderDetailReturn(detail, dto);
                }else{
                    R r = purchaseOrderDetailFeignService.getById(details.getId(), SecurityConstants.FROM_IN);
                    if(!RUtil.isSuccess(r) || r.getData() == null){
                        throw new EmptyDataException();
                    }
                    PurchaseOrderDetail detail = BeanUtil.toBean(r.getData(), PurchaseOrderDetail.class);
                    save = AddReturnOrderTrans.initReturnOrderDetailTrans(detail);
                }
                save.setReturnSn(req.getReturnSn());
                if(!returnOrderDetailService.save(save)){
                    throw new ErrorDataException();
                }
            });
        }
        return true;
    }

    /**
     * 审核退货单
     * @param req
     * @return
     */
    @Override
    public Boolean auditPassOrder(EditReturnOrderReq req) {
        ReturnOrder order = new ReturnOrder();
        BeanUtil.copyProperties(req,order);
        if(req.getReturnStatus()  == ReturnStatusEnum.adopt) {
            order.setReturnStatus(ReturnStatusEnum.adopt);
        }else{
            order.setReturnStatus(ReturnStatusEnum.failed);
        }
        order.setSumAmount(BigDecimal.ZERO);
        req.getEditDetails().forEach(val ->{
            if(req.getReturnStatus()  == ReturnStatusEnum.adopt) {
                val.setReturnStatus(ReturnStatusEnum.adopt);
                val.setGoodsAmount(val.getGoodsNum().multiply(val.getGoodsPrice()));
                order.setSumAmount(order.getSumAmount().add(val.getGoodsAmount()));
            }else{
                val.setReturnStatus(ReturnStatusEnum.failed);
            }
            if(!returnOrderDetailService.updateById(val)){
                throw new ErrorDataException();
            }
        });
        order.setTotalAmount(order.getSumAmount().add(order.getOtherAmount()));
        if(!returnOrderService.updateById(order)){
            throw new ErrorDataException();
        }
        return true;
    }

    /**
     * 根据退货单创建入库单
     * @param req
     * @return
     */
    @Override
    public Boolean auditPassReturnOrder(EditReturnOrderReq req) {
        ReturnOrder order = new ReturnOrder();
        BeanUtil.copyProperties(req,order);
        order.setReturnStatus(ReturnStatusEnum.success);
        order.setSumAmount(BigDecimal.ZERO);
        String esn = scmIncrementUtil.inrcSnByClass(EnterWarehouse.class, NumberPrefixConstant.ENTER_WAREHOUSE_SN_PRE);
        if(order.getReturnStatus() == ReturnStatusEnum.adopt){
            EnterWarehouse warehouse = AddReturnOrderTrans.initEnterWarehouseTrans(order);
            warehouse.setWarehouseSn(esn);
            warehouse.setWarehouseSn(req.getWarehouseId());
            if(!RUtil.isSuccess(enterWarehouseFeignService.save(warehouse,SecurityConstants.FROM_IN))){
                throw new ErrorDataException();
            }
        }
        req.getEditDetails().forEach(detail -> {
            if(null == returnOrderDetailService.getById(detail.getId())){
                throw new EmptyDataException();
            }
            detail.setGoodsAmount(detail.getGoodsNum().multiply(detail.getGoodsPrice()));
            order.setSumAmount(order.getSumAmount().add(detail.getGoodsAmount()));
            if(order.getReturnStatus() == ReturnStatusEnum.goods_back || order.getReturnStatus() == ReturnStatusEnum.adopt){
                ProductInfo info = AddReturnOrderTrans.initProductInfoTrans(detail);
                info.setProductSn(scmIncrementUtil.inrcSnByClass(ProductInfo.class, NumberPrefixConstant.PRODUCT_INFO_SN_PRE));
                if(!RUtil.isSuccess(productInfoFeignService.save(info, SecurityConstants.FROM_IN))){
                    throw new ErrorDataException();
                }
                EnterWarehouseDetail enterWarehouseDetail = AddReturnOrderTrans.initEnterWarehouseDetailsTrans(detail, info);
                enterWarehouseDetail.setEnterWarehouseSn(esn);
                enterWarehouseDetail.setTenantId(null);
                enterWarehouseDetail.setWarehouseSn(req.getWarehouseId());
                if(!RUtil.isSuccess(enterWarehouseDetailFeignService.save(enterWarehouseDetail,SecurityConstants.FROM_IN))){
                    throw new ErrorDataException();
                }
            }else{
                throw new ErrorDataException();
            }
            detail.setReturnStatus(ReturnStatusEnum.success);
            if(!returnOrderDetailService.updateById(detail)){
                throw new ErrorDataException();
            }
        });
        order.setTotalAmount(order.getSumAmount().add(order.getOtherAmount()));
        if(!returnOrderService.updateById(order)){
            throw new ErrorDataException();
        }
        return true;
    }



    /**
     * 根据报价单创建退货单
     * @param req
     * @return
     */
    @Override
    public Boolean addReturnOrderByOfferOrder(AddReturnOrderByOfferReq req) {
        if(req.getList().isEmpty()){
            throw new EmptyDataException();
        }
        ReturnOrder order = new ReturnOrder();
        order.setPmId(req.getPmId());
        order.setReturnType(ReturnTypeEnum.purchase);
        order.setReturnStatus(ReturnStatusEnum.wait);
        String sn = scmIncrementUtil.inrcSnByClass(ReturnOrder.class, NumberPrefixConstant.RETURN_ORDER_SN_PRE);
        order.setReturnSn(sn);
        order.setTotalAmount(BigDecimal.ZERO);
        order.setSumAmount(BigDecimal.ZERO);
        order.setOtherAmount(req.getOtherAmount());
        order.setGoodsNum(BigDecimal.ZERO);
        String supplierId = req.getList().get(0).getSupplierId();
        req.getList().forEach(item ->{
            if(item.getSupplierId().equals(supplierId)
                    || item.getStatus() == PdsOfferStatusEnum.bidding
                    || item.getShipStatus() == ShipStatusEnum.sendCargo){
                order.setGoodsNum(order.getGoodsNum().add(BigDecimal.ONE));
                order.setSumAmount(order.getSumAmount().add(item.getBuyNum().multiply(item.getDealPrice())));
                ReturnOrderDetail detail = new ReturnOrderDetail();
                detail.setPmId(item.getPmId());
                detail.setReturnStatus(ReturnStatusEnum.wait);
                detail.setReturnSn(sn);
                detail.setGoodsId(item.getGoodsId());
                detail.setGoodsImg(item.getGoodsImg());
                detail.setGoodsName(item.getGoodsName());
                detail.setGoodsModelId(item.getGoodsModelId());
                detail.setUnit(item.getUnit());
                detail.setReturnTime(LocalDateTime.now());
                detail.setGoodsNum(item.getBuyNum());
                detail.setGoodsPrice(item.getDealPrice());
                detail.setGoodsCategoryId(item.getGoodsCategoryId());
                detail.setGoodsAmount(item.getBuyNum().multiply(item.getDealPrice()));
                detail.setModelName(item.getModelName());
                if(!returnOrderDetailService.save(detail)){
                    throw new ErrorDataException();
                }
            }else{
                throw new ErrorDataException();
            }
        });
        return returnOrderService.save(order);
    }

    /**
     * 审核退货单并生成库存
     * @param req
     * @return
     */
    @Override
    public Boolean passReturnOrderAddStock(EditReturnOrderReq req) {
        ReturnOrder order = new ReturnOrder();
        BeanUtil.copyProperties(req,order);
        order.setSumAmount(BigDecimal.ZERO);
        req.getEditDetails().forEach(detail -> {
            if(null == returnOrderDetailService.getById(detail.getId())){
                throw new EmptyDataException();
            }
            detail.setGoodsAmount(detail.getGoodsNum().multiply(detail.getGoodsPrice()));
            order.setSumAmount(order.getSumAmount().add(detail.getGoodsAmount()));
            if(order.getReturnStatus() == ReturnStatusEnum.back || order.getReturnStatus() == ReturnStatusEnum.goods_back){
                WarehouseStock stock = new WarehouseStock();
                stock.setMerchantId(detail.getPmId());
                stock.setWarehouseId(req.getWarehouseId());
                stock.setGoodsCode(detail.getGoodsModelId());
                stock.setGoodsName(detail.getGoodsName());
                stock.setUnit(detail.getUnit());
                stock.setAttr(detail.getModelName());
                stock.setStockNum(detail.getGoodsNum());
                stock.setPrice(detail.getGoodsPrice());
                stock.setAmount(detail.getGoodsAmount().multiply(detail.getGoodsPrice()));
                stock.setInstockTime(LocalDateTime.now());
                scmAfterSalesUtils.saveWarehouseStock(stock);
            }else{
                throw new ErrorDataException();
            }
            detail.setReturnStatus(ReturnStatusEnum.success);
            if(!returnOrderDetailService.updateById(detail)){
                throw new ErrorDataException();
            }
        });
        order.setReturnStatus(ReturnStatusEnum.success);
        order.setTotalAmount(order.getSumAmount().add(order.getOtherAmount()));
        if(!returnOrderService.updateById(order)){
            throw new ErrorDataException();
        }
        return true;
    }

    /**
     * 确认收货
     * @param req
     * @return
     */
    @Override
    public Boolean receiptGoods(EditReturnOrderReq req) {
        ReturnOrder order = new ReturnOrder();
        BeanUtil.copyProperties(req, order);
        order.setReturnStatus(ReturnStatusEnum.goods_back);
        order.setSumAmount(BigDecimal.ZERO);
        req.getEditDetails().forEach(val -> {
            val.setReturnStatus(ReturnStatusEnum.goods_back);
            val.setGoodsAmount(val.getReceiptNum().multiply(val.getGoodsPrice()));
            order.setSumAmount(order.getSumAmount().add(val.getGoodsAmount()));
            val.setGoodsNum(val.getReceiptNum());
            if (!returnOrderDetailService.updateById(val)) {
                throw new ErrorDataException();
            }
        });
        order.setTotalAmount(order.getSumAmount().add(order.getOtherAmount()));
        if (!returnOrderService.updateById(order)) {
            throw new ErrorDataException();
        }
        return true;
    }


}
